//
//  PlayerMangerTool.m
//  EDCsfzs
//
//  Created by feng on 16/8/27.
//  Copyright © 2016年 牛高航. All rights reserved.
//

#import "PlayerMangerTool.h"
@interface PlayerMangerTool ()
@property(nonatomic,strong)AVPlayer*player;
@property(nonatomic,strong)AVPlayerItem*currentPlayerItem;
@property(nonatomic,strong)NSURL*currentURL;
@property (nonatomic,strong)id playerObserveObj;


@end
@implementation PlayerMangerTool

void my(int a)
{
    NSLog(@"你好 我是PlayerMangerTool 被初始化了");

}
void fengbaodongTestFunction (void)
{
    
    NSLog(@"APPDelegate 测试");
    
    
}


-(instancetype)init
{
    self=[super init];
    if (self) {
        my(3);
        
    }
    
    return self;
}

/**
 *      @author 冯宝东
 *
 *      初始化开始的状态
 *
 */
-(void)settingBeginStatus
{
    self.song_currentTime=@"00:00";
    self.song_totalTimes=@"--:--";
    self.precent=0.0;
    self.playerStatus=NO;

}





/**
 *      @author 冯宝东
 *
 *      根据URL初始化一个Item
 */
-(void)configeWithNewPlayerItemWithNetWorkURL:(NSString*)model_Url
{
    self.currentURL=[NSURL URLWithString:model_Url];
    [self settingBeginStatus];
    if (!_player&&!_player.currentItem)
    {
        _currentPlayerItem=[[AVPlayerItem alloc] initWithURL:_currentURL];
        _player=[[AVPlayer alloc] initWithPlayerItem:_currentPlayerItem];
        [self addPlayerAobsever];
        [self itemAddKVO_Observer];
        
        NSLog(@"第一次初始化模式");
        
    }else
    {

        [self itemRemoveKVO_Observer];
        
        _currentPlayerItem=[[AVPlayerItem alloc] initWithURL:_currentURL];
        [_player removeTimeObserver:_playerObserveObj];//移除player的观察者
        //重新block
        _player=[[AVPlayer alloc] initWithPlayerItem:_currentPlayerItem];
        [self addPlayerAobsever];
        //不知道为什么在 系统的检测block就不可以知道时间
        // [self.player replaceCurrentItemWithPlayerItem:_currentPlayerItem];
        NSLog(@"切换歌曲模式");
        [self itemAddKVO_Observer];
        
    }

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.player.currentItem];




}

-(void)playbackFinished:(NSNotification *)notification{

    self.playerStatus=NO;
    [_player  seekToTime:CMTimeMake(0.0, 1)];
    

}

/**
 *      @author 冯宝东
 *
 *      播放
 */
-(void)play
{

    [_player play];
    
    
}

/**
 *      @author 冯宝东
 *
 *      暂停
 */
-(void)pause
{
    [_player pause];
    
}

/**
 *      @author 冯宝东
 *
 *      停止
 */
-(void)stop
{

    [_player pause];
    _player=nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];


}

/**
 *      @author 冯宝东
 *
 *      添加ItemKVO监控
 */

-(void)itemAddKVO_Observer
{
    //KVO
    [_currentPlayerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    [_currentPlayerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
    [_currentPlayerItem addObserver:self forKeyPath:@"playbackBufferEmpty" options:NSKeyValueObservingOptionNew context:nil];

    
}




/**
 *      @author 冯宝东
 *
 *      移除ItemKVO监控
 */
-(void)itemRemoveKVO_Observer
{
    [_currentPlayerItem removeObserver:self forKeyPath:@"status"];
    [_currentPlayerItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
    [_currentPlayerItem removeObserver:self forKeyPath:@"playbackBufferEmpty"];
    
}

-(void)addPlayerAobsever
{

    __weak typeof (PlayerMangerTool*) weakSelf=self;
    AVPlayerItem *currentTheItem= _player.currentItem;
    _playerObserveObj=[_player addPeriodicTimeObserverForInterval:CMTimeMake(1, 2) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        float currentTime=   CMTimeGetSeconds(time);
        NSString* currmT=[weakSelf getTimeStringByOneNumber:currentTime];
        weakSelf.song_currentTime=currmT;
       float durtionTime= CMTimeGetSeconds(currentTheItem.duration);
//        CGFloat totalTimes= theItem.duration.value/theItem.duration.timescale;
        NSString* totalT=[weakSelf getTimeStringByOneNumber:durtionTime];
//        weakSelf.precent=(currentTime*100.0)/(totalTimes*100.0);
        NSLog(@"播放时间：%@  总时间：%@",currmT,totalT);
        
    }];




}

- (void)observeValueForKeyPath:(nullable NSString *)keyPath ofObject:(nullable id)object change:(nullable NSDictionary<NSString*, id> *)change context:(nullable void *)context {
    
    if ([keyPath isEqualToString:@"status"]) {
        AVPlayerItemStatus status = _currentPlayerItem.status;
        switch (status) {
            case AVPlayerItemStatusReadyToPlay:
            {
                NSLog(@"AVPlayerItemStatusReadyToPlay");
                CMTime itemTime=_player.currentItem.duration;
                CGFloat totalTimes= itemTime.value/itemTime.timescale;
                self.song_totalTimes=[self getTimeStringByOneNumber:totalTimes];
                NSLog(@"这首歌的总时间为：%@",self.song_totalTimes);


                
                
            }
                break;
            case AVPlayerItemStatusUnknown:
            {
                NSLog(@"AVPlayerItemStatusUnknown");
            }
                break;
            case AVPlayerItemStatusFailed:
            {
                NSLog(@"AVPlayerItemStatusFailed");

            }
                break;
                
            default:
                break;
        }
    } else if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
        
        NSLog(@"%@",_player.currentItem.loadedTimeRanges);
        
        
        
    } else if ([keyPath isEqualToString:@"playbackBufferEmpty"]) {
        
        
        
    }
}

/**
 *      @author 冯宝东
 *
 *      拦截模式
 */

-(void)setPlayerStatus:(BOOL)playerStatus
{
    _playerStatus=playerStatus;
    //设置成播放模式
    if (_playerStatus&&_player.rate<0.1)
    {
        [self play];
    //设置成暂停模式
    }else
    {
    [self pause];
    }

}

#pragma mark --------------private

-(NSString*)getTimeStringByOneNumber:(CGFloat)number
{
    NSInteger indexTime=ceil(number);
    NSInteger minInt=indexTime/60;
    NSInteger secInt=indexTime%60;
    NSString *timeStr=[NSString stringWithFormat:@"%02zd:%02zd",minInt,secInt];
    return timeStr;
}


-(void)dealloc
{
    NSLog(@"%s",__FUNCTION__);
    [self itemRemoveKVO_Observer];
    [_player removeTimeObserver:_playerObserveObj];
    [self stop];
    fengbaodongTestFunction();

}





@end
